package com.wish;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WordToPdf {
    public static void word2pdf(String wordPath, String pdfPath) throws IOException {
        InputStream docxInputStream = null;
        OutputStream outputStream = null;
        try {
            // 原word地址
            docxInputStream = Files.newInputStream(Paths.get(wordPath));
            // 转换后pdf生成地址
            outputStream = Files.newOutputStream(Paths.get(pdfPath));
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).execute();
            // 关闭
            converter.shutDown();
            // 关闭
            outputStream.close();
            // 关闭
            docxInputStream.close();
        } catch (Exception e) {
            System.out.println("[documents4J] word转pdf失败:" + e.toString());
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (docxInputStream != null) {
                docxInputStream.close();
            }
        }
    }
}

